﻿using CommHelper;
using NX5Web.Entities;
using NX5Web.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web.Http;
using System.Web.Services.Description;

namespace NX5Web.Controllers
{
    public class EncryptController : ApiController
    {
        public static Dictionary<String, DateTime> KeyList = new Dictionary<string, DateTime>();


        public static string Decrypt(String key,string value)
        { 
            Byte[] toEncryptArray = Convert.FromBase64String(value);
            using (RijndaelManaged rm = new RijndaelManaged())
            {
                rm.Key = Encoding.UTF8.GetBytes(key);
                rm.IV = Encoding.UTF8.GetBytes(key);
                rm.Mode = CipherMode.CBC;
                rm.Padding = PaddingMode.PKCS7;
                rm.FeedbackSize = 128;
                ICryptoTransform encryptor = rm.CreateDecryptor(rm.Key, rm.IV);
                Byte[] resultArray = encryptor.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                return Encoding.UTF8.GetString(resultArray);
            }
        }

        //[HttpGet]
        //public IHttpActionResult CorKey(String DESC,String Key)
        //{
        //    String Data = Decrypt(Key, DESC);
        //    ApiHttpRequest apiHttpRequest = new ApiHttpRequest
        //    {
        //        status = true,
        //        data = Data
        //    };
        //    return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, apiHttpRequest)); 
        //}

        [HttpGet]
        public IHttpActionResult GetKeys()
        {
            ApiHttpRequest apiHttpRequest = new ApiHttpRequest
            {
                status = true,
                data = Newtonsoft.Json.JsonConvert.SerializeObject(KeyList)
            };
            return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, apiHttpRequest));
        }

        public static object locker = new object();

        [HttpPost]
        public IHttpActionResult GetKey()
        {
            String Key = Guid.NewGuid().ToString().Replace("-", "");
            lock (locker)
            {
                if (!KeyList.ContainsKey(Key))
                {
                    KeyList.Add(Key, DateTime.Now);
                }
            }
            ApiHttpRequest apiHttpRequest = new ApiHttpRequest
            {
                status = true,
                data = Key
            };
            return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, apiHttpRequest));
             
        }
    }
}